﻿using System;
using UnityEngine;

public class AndroidUtil
{
    /// <summary>
    /// Android的冒泡提示
    /// </summary>
    static public void ToastText(object str)
    {
#if UNITY_ANDROID
        using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                AndroidJavaClass toast = new AndroidJavaClass("android.widget.Toast");
                AndroidJavaObject context = currentActivity.Call<AndroidJavaObject>("getApplicationContext");
                currentActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
                {
                    AndroidJavaObject javaString = new AndroidJavaObject("java.lang.String", str.ToString());
                    toast.CallStatic<AndroidJavaObject>("makeText", context, javaString, toast.GetStatic<int>("LENGTH_SHORT")).Call("show");
                }
                ));
            }
        }
#endif
    }

    /// <summary>
    /// 返回手机电量
    /// 一个百分比数字，比如电量是93%，则这个数字是93
    /// </summary>
    static public int GetBatteryLevel()
    {
        int level = -1;
#if UNITY_ANDROID
        using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                AndroidJavaObject ifilter = new AndroidJavaObject("android.content.IntentFilter", "android.intent.action.BATTERY_CHANGED");
                AndroidJavaObject intent = currentActivity.Call<AndroidJavaObject>("getApplicationContext").Call<AndroidJavaObject>("registerReceiver", null, ifilter);
                int rawlevel = intent.Call<int>("getIntExtra", "level", 0);//获得当前电量
                int scale = intent.Call<int>("getIntExtra", "scale", 0);//获得总电量
                int status = intent.Call<int>("getIntExtra", "status", 0);//电池充电状态
                int health = intent.Call<int>("getIntExtra", "health", 0);//电池健康状况
                int batteryV = intent.Call<int>("getIntExtra", "voltage", 0);  //电池电压(mv)   
                int temperature = intent.Call<int>("getIntExtra", "temperature", 0);  //电池温度(数值)  
                double T = temperature / 10.0; //电池摄氏温度，默认获取的非摄氏温度值，需做一下运算转换  
                if (rawlevel > 0 && scale > 0)
                {
                    level = (rawlevel * 100) / scale;
                    //Debug.Log("现在的电量是:" + level + "%");
                }

                if (health == 2)
                {
                    //Debug.Log( "电池状态很好");
                }

                if (status == 2)//充电标记2
                {
                    //Debug.Log("电池充电中...");
                }
                else
                {
                    //Debug.Log("电池放电中...");
                }
            }
        }
#endif
        return level;
    }

    /// <summary>
    /// 返回wifi信号强度
    /// 得到的值是一个0到-100的区间值，是一个int型数据，其中0到-50表示信号最好，-50到-70表示信号偏差，小于-70表示最差，有可能连接不上或者掉线
    /// </summary>
    static public int GetWifiLevel()
    {
        int level = -1;
#if UNITY_ANDROID
        using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                AndroidJavaObject wifi_service = currentActivity.Call<AndroidJavaObject>("getSystemService", "wifi");
                if (wifi_service != null)
                {
                    AndroidJavaObject wifiInfo = wifi_service.Call<AndroidJavaObject>("getConnectionInfo");
                    if (wifiInfo != null)
                    {
                        level = wifiInfo.Call<int>("getRssi");
                    }
                }
            }
        }
#endif
        return level;
    }

    /// <summary>
    /// 获取手机剩余内存
    /// </summary>
    public static long GetAvailableMemory()
    {
        long size = 0;
#if UNITY_ANDROID
        using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                AndroidJavaObject am = currentActivity.Call<AndroidJavaObject>("getSystemService", "activity");
                if (am != null)
                {
                    AndroidJavaObject mi = new AndroidJavaObject("android.app.ActivityManager$MemoryInfo");
                    am.Call("getMemoryInfo", mi);
                    size = mi.Get<long>("availMem");
                }
            }
        }
#endif
        return size;
    }

    /// <summary>
    /// 获取当前占用内存
    /// </summary>
    public static long GetCurProgressUsedMemory()
    {
        long size = 0;
#if UNITY_ANDROID
        using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                AndroidJavaObject am = currentActivity.Call<AndroidJavaObject>("getSystemService", "activity");
                if (am != null)
                {
                    // 包名
                    string packageName = currentActivity.Call<AndroidJavaObject>("getApplicationInfo").Get<string>("packageName");
                    // 通过调用ActivityManager的getRunningAppProcesses()方法获得系统里所有正在运行的进程
                    AndroidJavaObject appProcessList = am.Call<AndroidJavaObject>("getRunningAppProcesses");
                    int count = appProcessList.Call<int>("size");
                    for (int i = 0; i < count; i++)
                    {
                        AndroidJavaObject appProcessInfo = appProcessList.Call<AndroidJavaObject>("get", i);
                        // 进程ID号
                        int pid = appProcessInfo.Get<int>("pid");
                        // 用户ID 类似于Linux的权限不同，ID也就不同 比如 root等
                        int uid = appProcessInfo.Get<int>("uid");
                        // 进程名，默认是包名或者由属性android：process=""指定
                        string processName = appProcessInfo.Get<string>("processName");
                        // 获得该进程占用的内存
                        int[] myMempid = new int[] { pid };
                        // 此MemoryInfo位于android.os.Debug.MemoryInfo包中，用来统计进程的内存信息
                        AndroidJavaObject[] memoryInfo = am.Call<AndroidJavaObject[]>("getProcessMemoryInfo", myMempid);
                        // 获取进程占内存用信息 kb单位
                        int memSize = memoryInfo[0].Call<int>("getTotalPss");
                        // 匹配包名
                        if (processName.Equals(packageName))
                        {
                            size = memSize * 1024;
                            //Debug.Log("@@@@@@@@@@@@@ pid=" + pid + " uid=" + uid + "  " + processName + " == " + packageName + "  memSize=" + memSize);
                            break;
                        }
                    }
                }
            }
        }
#endif
        return size;
    }

    /// <summary>
    /// 获取总内存
    /// </summary>
    public static long GetTotalMemory()
    {
        long size = 0;
#if UNITY_ANDROID
        using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                string str1 = "/proc/meminfo";
                string str2 = "";
                try
                {
                    AndroidJavaObject localFileReader = new AndroidJavaObject("java.io.FileReader", str1);
                    AndroidJavaObject localBufferedReader = new AndroidJavaObject("java.io.BufferedReader", localFileReader, 8192);
                    str2 = localBufferedReader.Call<string>("readLine");
                    str2 = str2.Split(':')[1].Replace("kB", "");
                    size = long.Parse(str2) * 1024; // 获得系统总内存 单位kb
                    localBufferedReader.Call("close");
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                }
            }
        }
#endif
        return size;
    }

    /// <summary>
    /// 设置屏幕亮度 Brightness的有效范围是0~1，-1。 若设置为-1则跟随系统亮度
    /// </summary>
    public static void SetBrightness(float Brightness)
    {
#if UNITY_ANDROID
        using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                currentActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
                {
                    AndroidJavaObject Window = null, Attributes = null;
                    Window = currentActivity.Call<AndroidJavaObject>("getWindow");
                    Attributes = Window.Call<AndroidJavaObject>("getAttributes");
                    Attributes.Set("screenBrightness", Brightness);
                    Window.Call("setAttributes", Attributes);
                }));
            }
        }
#endif
    }

    /// <summary>
    /// 获取Manifest.xml中的VersionCode
    /// </summary>
    public static int GetVersionCode()
    {
        int versionCode = 0;
#if UNITY_ANDROID
        using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                AndroidJavaObject context = currentActivity.Call<AndroidJavaObject>("getApplicationContext");
                AndroidJavaObject packageName = context.Call<AndroidJavaObject>("getPackageName");
                AndroidJavaObject packageMgr = context.Call<AndroidJavaObject>("getPackageManager");
                AndroidJavaObject packageInfo = packageMgr.Call<AndroidJavaObject>("getPackageInfo", packageName, 0);
                versionCode = packageInfo.Get<int>("versionCode");
            }
        }
#endif
        return versionCode;
    }

    /// <summary>
    /// 获取安卓SDK的API版本号
    /// </summary>
    public static int GetAndroidVersion()
    {
#if UNITY_ANDROID
        var version = new AndroidJavaClass("android.os.Build$VERSION");
        var sdkInt = version.GetStatic<int>("SDK_INT");
        return sdkInt;
#else
        return 0;
#endif
    }

    /// <summary>
    /// 获取Manifest.xml中的UsesCleartextTraffic
    /// </summary>
    /// <param name="version">安卓SDK的API版本号</param>
    public static bool GetUsesCleartextTraffic(int version)
    {
#if UNITY_ANDROID
        if (version >= 23)
        {
            using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
            {
                using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
                {
                    AndroidJavaObject packageManager = currentActivity.Call<AndroidJavaObject>("getPackageManager");
                    AndroidJavaObject packageInfo = packageManager.Call<AndroidJavaObject>("getPackageInfo", Application.identifier, 0);
                    AndroidJavaObject applicationInfo = packageInfo.Get<AndroidJavaObject>("applicationInfo");

                    AndroidJavaClass ApplicationInfo = new AndroidJavaClass("android.content.pm.ApplicationInfo");
                    int FLAG_USES_CLEARTEXT_TRAFFIC = ApplicationInfo.GetStatic<int>("FLAG_USES_CLEARTEXT_TRAFFIC");

                    bool usesCleartextTraffic = (applicationInfo.Get<int>("flags") & FLAG_USES_CLEARTEXT_TRAFFIC) != 0;
                    return usesCleartextTraffic;
                }
            }
        }
#endif
        return false;
    }

    /// <summary>
    /// 是否是模拟器
    /// </summary>
    static public bool GetIsSimulator()
    {
#if UNITY_ANDROID
        using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
        {
            using (AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"))
            {
                //判断是否存在光传感器来判断是否为模拟器
                AndroidJavaObject sensorManager = currentActivity.Call<AndroidJavaObject>("getSystemService", "sensor");
                if (sensorManager != null)
                {
                    AndroidJavaObject sensor = sensorManager.Call<AndroidJavaObject>("getDefaultSensor", 5);    //光传感器
                    if (sensor == null)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }
#endif
        return false;
    }
}
